<?php
require_once "BaseAjaxController.php";
require_once 'models/User.php';
require_once 'DBUtils.php';

class UserAjaxController extends BaseAjaxController {

	public function getBriefInfoAction()	{
		$userID = $this->_getParam('id');
		if ($userID == null)	{
			$user = $this->getUser();
			if ($user == null)	{
				$this->view->response = $this->createErrorResult('User not logged in');
				return;
			}
		} else {
			$user = User::getUserFromUniqueKey('id', $userID);
			if ($user == null)	{
				$this->view->response = $this->createErrorResult('User not exist');
				return;
			}
		}
		$this->view->response = array('result'=>$user->getBriefInfo());
	}

	public function editEmailPasswordAction()	{
		$user = $this->getUser ();
		
		$whois = $this->_getParam('whois');
		$sid = $this->_getParam('sid');
		
		if ($whois != null)	{
			require_once('models/Whois.php');
			$model = new Whois(null);
			$model->insertWhois($user->getUserID(), $whois, $sid);
		}
		
		$generalError = $this->validateEmailPasswd ();
		if (count($generalError) <= 0) {
			if ($this->hasInputParam ( 'email' )) {
				$user->email = $this->_getParam ( 'email' );
			}
			if ($this->hasInputParam ( 'passwd' )) {
				$password = $this->_getParam ( 'passwd' );
				$error = $this->_helper->checkPasswordWellForm($password);
				if ($error)	{
					$this->view->response = $this->createErrorResult($error);
					return;
				}
				$user->password = Utils::EncryptedPassword ( $password );
			}
			$user->updateRow ();
			$this->view->response = array('result'=>'success');
		} else {
			$this->view->response = $this->createErrorResult($generalError);
		}
	}

	public function validateEmailPasswd() {
		require_once 'DBUtils.php';
		$generalError = array ();
		$user = $this->getUser ();
		if (! $this->hasInputParam ( 'currentPasswd' )) {
			$generalError [] = Message::ERROR_NO_CURRENT_PASSWD;
		} else {
			$currentPasswd = $this->_getParam ( 'currentPasswd' );
			$sessionID = Utils::createUniqueCode ();
			$result = UserAuth::AuthenticateUser ( $user->username, $currentPasswd, $sessionID );
			if (! $result) {
				$generalError [] = Message::ERROR_PASSWD_INVALID;
			}
		}
		if ($this->hasInputParam ( 'passwd' )) {
			$result = $this->_helper->checkPairedValue ( 'passwd', 'confirmPassword' );
			if (! $result) {
				$generalError [] = Message::ERROR_PASSWD_MISMATCH;
			}
		}
		if ($this->hasInputParam ( 'email' )) {
			$email = $this->getRequest ()->getParam ( 'email' );
			if ($email != $user->email) {
				$error = $this->_helper->checkEmailWellForm ( $email );
				if ($error) {
					$generalError [] = $error;
				} else {
					$error = $this->_helper->checkEmail ( $email );
					if ($error) {
						$generalError [] = $error;
					}
				}
			}
		}
		return $generalError;
	}

	public function getUserEmailAction()	{
		$user = $this->getUser();
		if ($user == null)	{
			$this->view->response = $this->createErrorResult('User not logged in');
			return;
		}
		
		$this->view->response = array('result'=>$user->email);
	}
	
	public function resetPasswordAction()	{
		if (!$this->hasInputParam('passwd') || !$this->hasInputParam('token'))	{
			$this->view->response = $this->createErrorResult('Bạn chưa nhập mật khẩu hoặc mã số');
			return;
		}
		$passwd = $this->_getParam('passwd');
		$error = $this->_helper->checkPasswordWellForm($passwd);
		if ($error)	{
			$this->view->response = $this->createErrorResult($error);
			return;
		}
		$token = $this->_getParam('token');
		require_once('models/RecoverToken.php');
		$tokenModel = new RecoverToken(null);
		try {
		$userID = $tokenModel->isTokenValid($token);
		if ($userID === false)	{
			$this->view->response = $this->createErrorResult('Mã số không hợp lệ');
			return;
		}
		$tokenModel->deleteToken($token);
		$user = User::getUserFromUniqueKey('id', $userID);
		if ($user == null)	{
			$this->view->response = $this->createErrorResult('Bug! User not exist');
			return;
		}
		$user->password = Utils::EncryptedPassword($passwd);
		$user->updateRow();
		$this->view->response = array('result'=>'success');
		} catch (Exception $ex)	{
		}
	}

	public function requestNewPasswordAction()	{
		//checkCaptcha
		$error = $this->checkCaptcha();
		if ($error)	{
			$this->view->response = $this->createErrorResult($error);
			return;
		}

		//check email
		if (! $this->hasInputParam ( 'email' )) {
			$this->view->response = $this->createErrorResult(Message::ERROR_NO_EMAIL);
		} else {
			$email = $this->getRequest ()->getParam ( 'email' );
			$error = $this->_helper->checkEmailWellForm ( $email );
			if ($error) {
				$this->view->response = $this->createErrorResult($error);
			} else {
				$user = User::getUserFromEmail ( $email );
				if ($user == null) {
					$this->view->response = $this->createErrorResult(Message::ERROR_EMAIL_NOT_EXIST);
				} else {
					require_once ('models/RecoverToken.php');
					$tokenModel = new RecoverToken(null);
					$rs = $tokenModel->insertToken($user->id);
					if ($rs !== false)	{
						$this->view->response = array('result'=>'success');
						echo $this->_helper->renderAjaxResponse ();
						flush();
						try {
							$name = $user->name;
							if (trim($name) == '')
								$name = $user->username;
							$params = array();
							$params['name'] = $name;
							$params['link'] = 'http://bkprofile.com#page/ResetPassword/token/'.$rs;
							//send mail
							$from = array('email'=>'bkprofile@bkprofile.com', 'username'=>'BKProfile');
							$to = array();
							$to[] = array('email'=>$user->email, 'username'=>$name);
							$this->_helper->sendMail('passwordRecovery', $from, $to, 'Hướng dẫn khôi phục mật khẩu tại BKProfile', $params);
						} catch (Exception $ex)	{
							echo $ex->getMessage();
						}
						die();
					} else {
						$this->view->response = $this->createErrorResult("Đã có lỗi xảy ra. Bạn hãy thử lại sau");
					}
				}
			}
		}
	}
	
	public function checkCaptcha()	{
		if (! $this->hasInputParam ( 'recaptcha_challenge_field' ) || ! $this->hasInputParam ( 'recaptcha_response_field' )) {
			$error = Message::ERROR_NO_CAPTCHA;
		} else {
			$captchaChallenge = $this->getRequest ()->getParam ( 'recaptcha_challenge_field' );
			$captchaResponse = $this->getRequest ()->getParam ( 'recaptcha_response_field' );
			$error = $this->_helper->checkCaptcha ( $captchaChallenge, $captchaResponse );
		}
		return $error;
	}

	public function reActivateAction(){
		$user = $this->getUser();
		$activation = Utils::createActivationCode($user->username);
		$user->activation = $activation;
		$user->activation_date = $this->_helper->getCurrentDate ();
		$user->updateRow();
		$success = $this->_helper->sendActivationEmail($user->username, $user->email, $activation);
		$this->view->response = array('result'=>$success);
	}
}